package com.lczyfz.campusinfo.modules.wechat.web;

import com.lczyfz.campusinfo.common.utils.IdGen;
import com.lczyfz.campusinfo.common.utils.SpringContextHolder;
import com.lczyfz.campusinfo.common.web.BaseController;
import com.lczyfz.campusinfo.modules.sys.entity.User;
import com.lczyfz.campusinfo.modules.sys.service.SystemService;
import com.lczyfz.campusinfo.modules.user.dao.CampusinfoUserDao;
import com.lczyfz.campusinfo.modules.user.service.CampusinfoUserService;
import com.lczyfz.campusinfo.modules.user.utils.ServerResponse;
import com.lczyfz.campusinfo.modules.wechat.entity.AccessToken;
import com.lczyfz.campusinfo.modules.wechat.entity.InMessage;
import com.lczyfz.campusinfo.modules.wechat.entity.WeChatUser;
import com.lczyfz.campusinfo.modules.wechat.service.WeChatService;
import com.lczyfz.campusinfo.common.utils.DateUtils;

import com.lczyfz.campusinfo.modules.wechat.utils.MsgType;
import com.lczyfz.campusinfo.modules.wechat.utils.WeChatUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;


/**
 * 微信Controller
 * @author maple
 * @version 2017-01-19
 */
@Controller
@RequestMapping(value = "${apiPath}/wechat" )

public class WeChatController extends BaseController {

    @Autowired
    private CampusinfoUserService campusinfoUserService;
    @Autowired
    private WeChatService weChatService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private CampusinfoUserDao campusinfoUserDao;

    @RequestMapping(value = "mainurl" ,method = RequestMethod.GET)
    @ResponseBody
    public String mainurl(String signature,String timestamp,String nonce,String echostr) {
        logger.debug("signature" + signature);
        logger.debug("timestamp" + timestamp);
        logger.debug("nonce" + nonce);
        logger.debug("echostr" + echostr);
        return echostr;
    }
    @RequestMapping(value = "mainurl" ,method = RequestMethod.POST)
    public void mainurl(@RequestBody InMessage inMessage, HttpServletResponse response, HttpServletRequest request) {

        logger.debug("inMessage = " + inMessage);
        System.out.println("inMessage = " + inMessage);
        String servername = inMessage.getToUserName();// 服务端
        String custermname = inMessage.getFromUserName();// 客户端
        Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;// 返回时间

        if (inMessage.getEvent().equals(MsgType.EVENT_TYPE_SUBSCRIBE)) {
                //关注/取消关注事件
                logger.debug("用户关注");
                String content = "";
                //获取当前微信用户信息
                WeChatUser weChatUser = weChatService.getWeChatUserInfo(custermname);
                logger.debug(weChatUser.toString());
                // 如果已存在openid 就不需要注册  否则
                ServerResponse serverResponse = campusinfoUserService.isUserByOpenid(weChatUser.getOpenid());
                if (serverResponse.isSuccess()) {
                    //该微信用户已经存在
                    System.err.println("已关注");
                    content = weChatUser.getNickname() + ",欢迎回来！";
                } else {
                    content = weChatUser.getNickname() + "欢迎加入我们";
                    //创建系统用户
                    User user = new User();
                    user.setId(IdGen.uuid());
                    user.setOpenId(weChatUser.getOpenid());
                    user.setUnionId(weChatUser.getUnionid());
                    //设置默认loginName
                    String loginName = "fdzy_"+DateUtils.getCurrentDateAndTime()+DateUtils.getNewRandomCode(5)+"wxper";
                    user.setLoginName(loginName);
                    String nickName = weChatUser.getNickname();
                    if (nickName != null && nickName.length() > 0) {
                        nickName = nickName.replaceAll("[\ud800\udc00-\udbff\udfff\ud800-\udfff]", "");
                    }
                    user.setName(nickName);
                    user.setPassword("02a3f0772fcca9f415adc990734b45c6f059c7d33ee28362c4852032");
                    user.setLoginFlag("1");
                    user.setUserType("2");
                    user.setCreateBy(systemService.getUser("1"));
                    user.setUpdateBy(systemService.getUser("1"));
                    user.setUpdateDate(new Date());
                    user.setCreateDate(user.getUpdateDate());
                    int resultCount = campusinfoUserDao.insertUser(user);
                    if(resultCount == 0){
                        logger.debug("注册失败");
                    }
                    logger.debug("注册成功");
                    //新用户注册 end
                }
                boolean result = weChatService.replyTextMessage(response, custermname, servername, returnTime, MsgType.REQ_MESSAGE_TYPE_TEXT, content);
            }
        return;
    }

    @RequestMapping(value = "user/info")
    @ResponseBody
    public WeChatUser userInfo() {
        String openid = "onmiuweatgGf60_ZijUH1qv1LU60";
        WeChatUser weChatUser = weChatService.getWeChatUserInfo(openid);
        return weChatUser;
    }

    //登陆平台 进入首页
    @RequestMapping(value = "redirectUriHomePage")
    public String redirectUriHomePage(String code, String state, HttpServletRequest request, Model model) {

        logger.debug("code = " + code);
        logger.debug("state = " + state);
        //获取token以及用户信息
        AccessToken accessToken = WeChatUtils.getAuthorizationAccessTokenByCode(code);
        logger.debug("accessToken = " + accessToken);

        //进行平台登录操作
        try{
            User user = weChatService.doLoginMainPlatform(request, accessToken.getOpenid());
            logger.debug("userId"+user);
            getSystemService().updateUserLoginInfo(user);
        }catch (AuthenticationException e) {
            logger.debug("AuthenticationException = " + e.getMessage());
        }
//        System.err.println("重定向");
       return "redirect:"  + frontPath +"/campusinfo/homepage";
 //       System.err.println("转发");
    }

    //登陆平台 进入关于我们
    @RequestMapping(value = "redirectUriAboutUs")
    public String redirectUriAboutUs(String code, String state, HttpServletRequest request, Model model) {

        logger.debug("code = " + code);
        logger.debug("state = " + state);
        //获取token以及用户信息
        AccessToken accessToken = WeChatUtils.getAuthorizationAccessTokenByCode(code);
        logger.debug("accessToken = " + accessToken);

        //进行平台登录操作
        try{
            User user = weChatService.doLoginMainPlatform(request, accessToken.getOpenid());
            logger.debug("userId"+user);
            getSystemService().updateUserLoginInfo(user);
        }catch (AuthenticationException e) {
            logger.debug("AuthenticationException = " + e.getMessage());
        }

        return "redirect:"  + frontPath +"/campusinfo/aboutUs";
    }

    //登陆平台 帮助中心
    @RequestMapping(value = "redirectUriAboutHelpCenter")
    public String redirectUriAboutHelpCenter(String code, String state, HttpServletRequest request, Model model) {
        logger.debug("code = " + code);
        logger.debug("state = " + state);
        //获取token以及用户信息
        AccessToken accessToken = WeChatUtils.getAuthorizationAccessTokenByCode(code);
        logger.debug("accessToken = " + accessToken);
        //进行平台登录操作
        try {
            User user = weChatService.doLoginMainPlatform(request, accessToken.getOpenid());
            logger.debug("userId" + user);
            getSystemService().updateUserLoginInfo(user);
        } catch (AuthenticationException e) {
            logger.debug("AuthenticationException = " + e.getMessage());
        }

        return "redirect:"  + frontPath +"/campusinfo/helpCenter?"+ UUID.randomUUID();
    }


    /**
     * 获取系统业务对象
     */
    public SystemService getSystemService() {
        if (systemService == null){
            systemService = SpringContextHolder.getBean(SystemService.class);
        }
        return systemService;
    }
}
